//
//  PhotoBrowserCell.swift
//  Weibo
//
//  Created by apple on 15/12/22.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
///定义个协议
protocol PhotoBrowserCellDelegate: NSObjectProtocol {
 // 点击图片的事件
    func PhotoBrowserCellDidTapImage()
}
//照片查看cell
class PhotoBrowserCell: UICollectionViewCell {
    
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    //MARK: 监听方法
    @objc private func tapImage() {

        photoDelegate?.PhotoBrowserCellDidTapImage()
        
    }
    
    
    //MARK: 图像URL
    var imageURL: NSURL? {
    
        didSet{
            guard let url = imageURL else {
            
                return
            }
            //0 恢复scrollView
            resetScrollView()
            //1 url缩略图的地址
            //1> 从磁盘加载缩略图的图像
            let placehoderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
            
            setPlaceHolder(placehoderImage)
            
            //2 异步加载大图 sd_webImage 有一个功能 一旦设置了url 准备异步加载
            //清除之前的图片 如果之前的图片也是异步下载 但是没有完成 取消之前的异步操作
            //如果url对应的图片已经被缓存 直接从磁盘读取 不会在走网络加载
            
            // 几乎多有的第三方框架，进度回调都是异步加载的
            //原因： 
            //1 不是所有的程序都需要进度回调
            //2 进度回调的频率非常高 如果在主线程 会造成主线程卡顿
            //3 使用进度回调 要求界面上跟进度变化的UI不多， 而且不会频繁更新
            
            imageView.sd_setImageWithURL(bmiddleURL(url),
                placeholderImage: nil,//此处设置为nil
                options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed], progress: { (current, total) -> Void in
                    
                    //判断是否异步 
//                    print(NSThread.currentThread())
                    //更新进度
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeHoder.progress = CGFloat(current) / CGFloat(total)
                    })
                    
                }) { (image, _, _, _) -> Void in
                    
                    //判断图像是否下载成功
                    if image == nil {
                        
                    SVProgressHUD.showInfoWithStatus("您的网络不给力")
                        return
                        
                    }
                    
                    //隐藏占位图像
                    self.placeHoder.hidden = true
                    //设置图像试图的位置
                    self.setPosition(image)
            }

        }
    }
    ///设置占位图像试图的内容
    private func setPlaceHolder(image: UIImage?) {
        
       placeHoder.hidden = false
        
       placeHoder.image = image
       placeHoder.sizeToFit()
        placeHoder.center = scrollView.center
        
    }
    ///重设scrollView的内容属性
    private func resetScrollView() {
        
        //重设imageView的内容属性
        imageView.transform = CGAffineTransformIdentity
    
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    private func setPosition(image: UIImage) {
        //自动设置大小
        let size = self.displaySize(image)
        //判断图片高度
        if size.height < scrollView.bounds.height {
        
            //上下居中显示
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            //内容边距 会调整控件位置 但是不会影响控件的滚动
            let y = (scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        } else {
        
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollView.contentSize = size
        }

    }
    
    //根据scrollView的宽度计算等比例缩放之后的尺寸
    private func displaySize(image:UIImage) -> CGSize {
    
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return  CGSize(width: w, height: h)
    }
    ///返回中等尺寸图片 URL 
    private func bmiddleURL(url: NSURL) -> NSURL {
    
        print(url)
        //1 转换成 string
        var urlString = url.absoluteString
        
        //2 替换单词
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: urlString)!
    }
    //MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置布局
    private func setupUI() {
        //1 添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeHoder)
        
        //2 设置布局
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        //3 设置scrollView的缩放
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        // 4 添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
        

    }
    
    //MARK： 懒加载控件
    private lazy var scrollView: UIScrollView = UIScrollView()
    
    lazy var imageView: UIImageView = UIImageView()
    
    lazy var placeHoder: ProgressImageView = ProgressImageView()
    
}

extension PhotoBrowserCell: UIScrollViewDelegate {
    //返回被缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    //这个方法缩放完成后执行一次
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        print("缩放完成\(view)\(view?.bounds)")
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        
        //设置间距
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    
    //这个方法只要缩放就会被调用  改变的transform
    func scrollViewDidZoom(scrollView: UIScrollView) {
        print(imageView.transform)
    }
}
